using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Windows;
using System.Windows.Data;
using System.Windows.Input;
using System.Windows.Navigation;
using CashBankIn.CashBankInServices;
using CashBankIn.CoaServices;
using CashBankIn.DepartemenServices;
using CashBankIn.CustomerServices;
using CashBankIn.SalesInvoiceServices;
using Lib;
using Lib.Helper;
using MSIACCSL2.Command;
using WcfService1.DTO;
using GetListByCriteriaCompletedEventArgs = CashBankIn.CashBankInServices.GetListByCriteriaCompletedEventArgs;
using GetListCompletedEventArgs = CashBankIn.CashBankInServices.GetListCompletedEventArgs;
using SaveCompletedEventArgs = CashBankIn.CashBankInServices.SaveCompletedEventArgs;


namespace CashBankIn.ViewModels
{
    public class CashBankInViewModel : ViewModelBase
    {
        #region Delegates

        public delegate void Completed(Object param);

        #endregion

        private static string OrderType;
        private static string PropertySort;
        public static Mode mode;
        private static FrmAdd frmAdd;
        private static NavigationService _NavigationService;
        public static Completed OnSearchCompleted;

        private readonly SalesInvoiceServicesClient salesInvoiceClient;
        private readonly CashBankInServicesClient client;
        private readonly DepartemenServicesClient CostClient;
        private readonly CustomerServicesClient CustomerClient;
        private readonly CoaServicesClient CoaClient;
        private readonly ValidationHandler validationHandler;
        private int CurrentPage;
        private ObservableCollection<int> Pages;
        private bool _IsBusy;
        private CashBankInDTO _CashBankIn;
        private PagedCollectionView _CashBankIns;
        private List<string> _errors;
        private Visibility _messageVisibility;
        private PagedCollectionView _pageSources;
        private string expression;
        private ObservableCollection<DepartemenDTO> _Departemens;
        private ObservableCollection<CustomerDTO> _Customers;
        private bool _IsPayment;
        private Visibility _PaymentVisibility;
        private Visibility _NonPaymentVisibility;
        private ObservableCollection<CoaDTO> _Coas;


        public CashBankInViewModel()
        {
            if (!DesignerProperties.IsInDesignTool)
            {
                salesInvoiceClient = new SalesInvoiceServicesClient();
                CustomerClient = new CustomerServicesClient();
                client = new CashBankInServicesClient();
                CostClient = new DepartemenServicesClient();
                CoaClient = new CoaServicesClient();
                OnPageChanged = new DelegateCommand(PageIndexChanged, CanPageIndexChanged);
                Save = new DelegateCommand(SaveCashBankIn, CanSave);
                New = new DelegateCommand(NewCashBankIn, CanNew);
                Unload = new DelegateCommand(Release, CanUnload);
                SearchCommand = new DelegateCommand(SearchCashBankIn, CanSearch);
                SearchResultCommand = new DelegateCommand(SearchResult, CanSearchResult);
                CancelCommand = new DelegateCommand(Cancel, CanCancelCommand);
                validationHandler = new ValidationHandler();
                MessageVisibility = Visibility.Collapsed;
                PaymentVisibility = Visibility.Collapsed;
                NonPaymentVisibility = Visibility.Visible;
               
                

                if (mode == Mode.Edit)
                {
                   PrepareEdit();
                }
                else if (mode == Mode.Search)
                {
                    CashBankIn = new CashBankInDTO();
                }
                else if (mode == Mode.Add)
                {
                    PrepareAdd();
                }
                else
                {
                    GetList(1, null);
                }
            }
        }

        public void PrepareAdd()
        {
            CashBankIn = new CashBankInDTO();
            CashBankIn.CashBankInDetails = new ObservableCollection<CashBankInDetailDTO>();
            GetAllCustomer();
            GetCOAKasBank();
            IsPayment = false;
            GetDepartemens();
            GetSIAll();
        }

        public void PrepareEdit()
        {
            CashBankIn = (CashBankInDTO)Navigation.Args;
            GetCashBankIn(CashBankIn.NoVoucher);
            if (CashBankIn.CashBankInDetails == null)
                CashBankIn.CashBankInDetails = new ObservableCollection<CashBankInDetailDTO>();
            if (CashBankIn.CashBankInDetails.Count == 0)
                CashBankIn.CashBankInDetails.Add(new CashBankInDetailDTO());
           
        }

        public void GetCashBankIn(string noVoucher)
        {
            client.GetCashBankInCompleted += client_GetCashBankInCompleted;
            client.GetCashBankInAsync(noVoucher);
        }

        void client_GetCashBankInCompleted(object sender, GetCashBankInCompletedEventArgs e)
        {
            client.GetCashBankInCompleted -= client_GetCashBankInCompleted;
            CashBankIn = e.Result;
            GetAllCustomer();
            GetCOAKasBank();
            GetDepartemens();
            GetSIAll();
        }

        public PagedCollectionView CashBankIns
        {
            get { return _CashBankIns; }

            private set
            {
                if (CashBankIns == value) return;
                _CashBankIns = value;
                int i = (CurrentPage*30);
                foreach (object CashBankIn in CashBankIns)
                {
                    i += 1;

                    ((CashBankInDTO) CashBankIn).No = i;
                }
                FirePropertyChanged("CashBankIns");
                CashBankIns.CollectionChanged += CashBankIn_CollectionChanged;
            }
        }

        public PagedCollectionView PageSources
        {
            get { return _pageSources; }
            private set
            {
                if (PageSources == value) return;
                _pageSources = value;
                FirePropertyChanged("PageSources");
            }
        }


        public bool IsBusy
        {
            get { return _IsBusy; }
            internal set
            {
                _IsBusy = value;
                FirePropertyChanged("IsBusy");
            }
        }


        public long RecordCount { get; set; }

        //Buat binding ke child form waktu mau edit
        public CashBankInDTO CashBankIn
        {
            get { return _CashBankIn; }
            private set
            {
                if (CashBankIn == value) return;
                _CashBankIn = value;
                FirePropertyChanged("CashBankIn");
            }
        }


        public ICommand OnPageChanged { get; set; }
        public ICommand Save { get; set; }
        public ICommand New { get; set; }
        public ICommand Edit { get; set; }
        public ICommand Unload { get; set; }
        public ICommand SearchCommand { get; set; }
        public ICommand SearchResultCommand { get; set; }
        public ICommand CancelCommand { get; set; }

        public List<string> Errors
        {
            get { return _errors; }
            private set
            {
                if (Errors == value) return;
                _errors = value;
                FirePropertyChanged("Errors");
            }
        }

        public Visibility MessageVisibility
        {
            get { return _messageVisibility; }
            private set
            {
                if (MessageVisibility == value) return;
                _messageVisibility = value;
                FirePropertyChanged("MessageVisibility");
            }
        }


        public ObservableCollection<DepartemenDTO> Departemens
        {
            get { return _Departemens; }
            private set
            {
                if (Departemens == value) return;
                _Departemens = value;
                FirePropertyChanged("Departemens");
            }
        }

        public ObservableCollection<CustomerDTO> Customers
        {
            get { return _Customers; }
            private set
            {
                if (Customers == value) return;
                _Customers = value;
                FirePropertyChanged("Customers");
            }
        }


        public ObservableCollection<CoaDTO> Coas
        {
            get { return _Coas; }
            private set
            {
                if (Coas == value) return;
                _Coas = value;
                FirePropertyChanged("Coas");
            }
        }

        public void Complete(Object param)
        {
            OnSearchCompleted(param);
        }

        private void CashBankIn_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            if (((PagedCollectionView) sender).SortDescriptions.Count > 0)
            {
                if (((PagedCollectionView) sender).SortDescriptions[0].PropertyName.ToLower() == "no") return;

                PropertySort = ((PagedCollectionView) sender).SortDescriptions[0].PropertyName;
                if (string.IsNullOrEmpty(OrderType))
                {
                    OrderType = "ASC";
                }
                else
                {
                    OrderType = OrderType == "ASC" ? OrderType = "DESC" : OrderType = "ASC";
                }
                GetList(1, PropertySort);
            }
        }


        public void SaveCashBankIn(Object param)
        {
            Validate();
            if (Errors.Count > 0) return;
            //CashBankIn.created_by = GlobalVar.User.UserID;
            //CashBankIn.modified_by = GlobalVar.User.UserID;
            client.SaveCompleted += client_SaveCompleted;
            client.SaveAsync(CashBankIn);
            IsBusy = true;
        }

        private void client_SaveCompleted(object sender, SaveCompletedEventArgs e)
        {
            IsBusy = false;
            client.SaveCompleted -= client_SaveCompleted;
            if (e.Error != null)
            {
                MessageBox.Show(e.Error.Message);
                return;
            }
           
            if (e.Result)
            {
                mode = Mode.Idle;
                Navigation.MyNavigation.Navigate(new Uri("/EXT:CashBankIn.dll/Index", UriKind.Relative));
            }
        }


        public void GetList(int? page, string sortProp)
        {
            IsBusy = true;
            client.GetListCompleted += client_GetListCompleted;
            client.GetListAsync(page ?? 1, sortProp, OrderType);
        }

        private void client_GetListCompleted(object sender, GetListCompletedEventArgs e)
        {
            RecordCount = e.recordCount;
            if (PageSources == null) CreatePageNumber();
            client.GetListCompleted -= client_GetListCompleted;
            CashBankIns = new PagedCollectionView(e.Result);
            IsBusy = false;
            Complete(this);
        }


        private void NewCashBankIn(Object param)
        {
            mode = Mode.Add;
            Navigation.MyNavigation = (NavigationService) param;
            Navigation.MyNavigation.Navigate(new Uri("/EXT:CashBankIn.dll/FrmAdd", UriKind.Relative));
        }


        private void SearchCashBankIn(Object param)
        {
            mode = Mode.Search;
            CashBankIn = new CashBankInDTO();
            EventAggregator.PublishMessage("SearchCashBankIn", null, null);
            //EventAggregator.RegisterMessage("SearchCashBankInResult",(x,y)=>
            //                                                             {
            //                           CashBankInSearch((Dictionary<string, object>) x,(List<string>) y);                                      
            //                                                             });
            
        }


        private void SearchResult(Object param)
        {
            var criteria = new Dictionary<string, object>();

            foreach (PropertyInfo prop in CashBankIn.GetType().GetProperties())
            {
                if (prop.PropertyType == typeof(Decimal))
                {
                    if ((Decimal)prop.GetValue(CashBankIn, null) == 0) continue;
                }
                if (prop.PropertyType == typeof(Int32))
                {
                    if ((Int32)prop.GetValue(CashBankIn, null) == 0) continue;
                }
                if (prop.PropertyType == typeof(Int64))
                {
                    if ((Int64)prop.GetValue(CashBankIn, null) == 0) continue;
                }
                if (prop.PropertyType == typeof(Double))
                {
                    if ((Double)prop.GetValue(CashBankIn, null) == 0) continue;
                }
                if (prop.PropertyType == typeof(String))
                {
                    if (String.IsNullOrEmpty((String)prop.GetValue(CashBankIn, null))) continue;
                }
                if (prop.PropertyType == typeof(DateTime))
                {
                    if (prop.GetValue(CashBankIn, null).ToString().Contains("0001")) continue;
                }
                if (prop.GetValue(CashBankIn, null) == null) continue;
                if (prop.PropertyType.Name == "No") continue;
                if (prop.PropertyType.Name.Contains("Collection")) continue;

                if (prop.PropertyType.Name.ToLower().Contains("dto"))
                {
                    foreach (PropertyInfo propertyInfo in prop.GetValue(CashBankIn, null).GetType().GetProperties()
                        )
                    {
                        if (propertyInfo.Name.ToLower().Contains("id") || propertyInfo.Name.ToLower().Contains("kode") ||
                            propertyInfo.Name.ToLower().Contains("serial") ||
                            propertyInfo.Name.ToLower().Contains("code"))
                        {
                            criteria.Add(prop.Name, propertyInfo.GetValue(prop.GetValue(CashBankIn, null), null));
                            break;
                        }
                    }
                }
                else
                {
                    criteria.Add(prop.Name, prop.GetValue(CashBankIn, null));
                }
            }

            expression = string.Empty;
            if (param as bool? ?? false) expression = "OR";
            else expression = "AND";
            CashBankInSearch(criteria, expression);
            
        }

        private void CashBankInSearch(Dictionary<String, Object> criteria, string expression)
        {
            IsBusy = true;
            Complete(this);
            client.GetListByCriteriaCompleted += client_GetListByCriteriaCompleted;
            client.GetListByCriteriaAsync(criteria,expression,1);
        }

        private void client_GetListByCriteriaCompleted(object sender, GetListByCriteriaCompletedEventArgs e)
        {
            client.GetListByCriteriaCompleted -= client_GetListByCriteriaCompleted;
            CashBankIns = new PagedCollectionView(e.Result);
            RecordCount = e.recordCount;
            CreatePageNumber();
            IsBusy = false;
        }


        private void CreatePageNumber()
        {
            Pages = new ObservableCollection<int>();
            for (int i = 0; i < RecordCount; i++)
            {
                Pages.Add(i);
            }
            PageSources = new PagedCollectionView(Pages);
        }


        private void PageIndexChanged(Object pageIndex)
        {
            //Jika Pertama kali jangan di Getlagi
            CashBankIn = null;
            if (CashBankIns != null && CurrentPage != (int) pageIndex)
            {
                CurrentPage = (int) pageIndex;
                if (String.IsNullOrEmpty(PropertySort))
                    GetList((int) pageIndex + 1, null);
                else GetList((int) pageIndex + 1, PropertySort);
            }
        }


        public bool CanPageIndexChanged(Object param)
        {
            return true;
        }


        public bool CanSave(Object param)
        {
            return true;
        }


        public bool CanNew(Object param)
        {
            return true;
        }

        public bool CanEdit(Object param)
        {
            return true;
        }


        public bool CanUnload(Object param)
        {
            return true;
        }


        public bool CanSearch(Object param)
        {
            return true;
        }

        public bool CanSearchResult(Object param)
        {
            return true;
        }

        public bool CanCancelCommand(Object param)
        {
            return true;
        }


        public void Release(Object param)
        {
            param = null;
            CashBankIn = null;
            OrderType = null;
            PropertySort = null;
            mode = Mode.Idle;
        }


        public void Refresh()
        {
            if (CashBankIns == null)
                GetList(1, null);
            else
                Complete(this);
        }


        public void Validate(string error = null)
        {
            Errors = new List<string>();
          
            if (CashBankIn.CashBankAccount == null)
            {
                MessageBox.Show("Kas atau Bank belum diisi!");
            }

            if (CashBankIn.CashBankInDetails.Sum(x => x.Debit) != CashBankIn.CashBankInDetails.Sum(x => x.Kredit))
            {
                MessageBox.Show("CashBankIn tidak balance!");
                Errors.Add("CashBankIn tidak balance!");
            }
           
            if (CashBankIn.CashBankInDetails.Where(x=>x.SalesInvoice != null).Any(x=>x.Kredit > x.SalesInvoice.Total && x.SalesInvoice.Total > 0))
            {
                MessageBox.Show("Pembayaran tidak boleh melebihi piutang!");
                Errors.Add("Pembayaran tidak boleh melebihi piutang!");
            }

            if (Errors.Count > 0)
                MessageVisibility = Visibility.Visible;
            else
                MessageVisibility = Visibility.Collapsed;
        }

        public void Cancel(Object param)
        {
            mode = Mode.Idle;
            Navigation.MyNavigation.GoBack();
        }

   
        public ICommand GetLastNumberCommand { get; set; }
        public bool CanGetLastNumber (Object param)
        {
            return true;
        }


        public void GetAllCustomer()
        {
            CustomerClient.GetAllCustomerCompleted += CustomerClient_GetAllCustomerCompleted;
            CustomerClient.GetAllCustomerAsync();
        }

        void CustomerClient_GetAllCustomerCompleted(object sender, GetAllCustomerCompletedEventArgs e)
        {
            CustomerClient.GetAllCustomerCompleted -= CustomerClient_GetAllCustomerCompleted;
            Customers = e.Result;
            foreach (var cd in CashBankIn.CashBankInDetails)
            {
                cd.Customers = new ObservableCollection<CustomerDTO>(e.Result);
                if (cd.Customer != null)
                    cd.Customer = cd.Customers.FirstOrDefault(x => x.CustomerId == cd.Customer.CustomerId);
            }

        }


        public void GetSIAll()
        {
            salesInvoiceClient.GetSalesInvoiceByCustomerCompleted += salesInvoiceClient_GetSalesInvoiceByCustomerCompleted;
            salesInvoiceClient.GetSalesInvoiceByCustomerAsync(null);
        }

      

        public void GetSalesInvoiceByCustomer(Object param)
        {
            if (param == null)return;
            salesInvoiceClient.GetSalesInvoiceByCustomerCompleted += salesInvoiceClient_GetSalesInvoiceByCustomerCompleted;
            salesInvoiceClient.GetSalesInvoiceByCustomerAsync((CustomerDTO)param);
        }

        void salesInvoiceClient_GetSalesInvoiceByCustomerCompleted(object sender, GetSalesInvoiceByCustomerCompletedEventArgs e)
        {
            salesInvoiceClient.GetSalesInvoiceByCustomerCompleted -= salesInvoiceClient_GetSalesInvoiceByCustomerCompleted;
           foreach (var cashBankInDetail in CashBankIn.CashBankInDetails)
            {
                cashBankInDetail.SalesInvoices = e.Result;
                if(cashBankInDetail.SalesInvoice!=null)
                    cashBankInDetail.SalesInvoice =
                        e.Result.FirstOrDefault(x => x.SINo == cashBankInDetail.SalesInvoice.SINo);
            }
        }

        public Visibility PaymentVisibility
        {
            get { return _PaymentVisibility; }
            set
            {
                if (value == PaymentVisibility) return;
                _PaymentVisibility = value;
                FirePropertyChanged("PaymentVisibility");
            }
        }

        public Visibility NonPaymentVisibility
        {
            get { return _NonPaymentVisibility; }
            set
            {
                if (value == NonPaymentVisibility) return;
                _NonPaymentVisibility = value;
                FirePropertyChanged("NonPaymentVisibility");
            }
        }

        public bool IsPayment
        {
            get { return _IsPayment; }
            set
            {
                //if (value == _IsPayment) return;
                _IsPayment = value;
                FirePropertyChanged("IsPayment");
                if (IsPayment)
                {
                    PaymentVisibility = Visibility.Visible;
                    NonPaymentVisibility = Visibility.Collapsed;
                    foreach (var cd in CashBankIn.CashBankInDetails)
                    {
                        cd.PaymentVisibility = Visibility.Visible;
                        cd.NonPaymentVisibility = Visibility.Collapsed;
                    }
                }
                else
                {
                    PaymentVisibility = Visibility.Collapsed;
                    NonPaymentVisibility = Visibility.Visible;
                    foreach (var cd in CashBankIn.CashBankInDetails)
                    {
                        cd.PaymentVisibility = Visibility.Collapsed;
                        cd.NonPaymentVisibility = Visibility.Visible;
                    }
                }
            }
        }


        public void GetCOAKasBank()
        {
            CoaClient.GetCoaKasBankCompleted += CoaClient_GetCoaKasBankCompleted;
            CoaClient.GetCoaKasBankAsync();
        }

        void CoaClient_GetCoaKasBankCompleted(object sender, GetCoaKasBankCompletedEventArgs e)
        {
            CoaClient.GetCoaKasBankCompleted -= CoaClient_GetCoaKasBankCompleted;
            Coas = e.Result;
            if (CashBankIn.CashBankAccount != null)
                CashBankIn.CashBankAccount =
                    e.Result.FirstOrDefault(x => x.AccountNumber == CashBankIn.CashBankAccount.AccountNumber);

            //foreach (var cd in CashBankIn.CashBankInDetails)
            //{
            //    cd.Coas = e.Result;
            //    if (cd.FromAccount != null)
            //        cd.FromAccount = e.Result.FirstOrDefault(x => x.AccountNumber == cd.FromAccount.AccountNumber);
            //}
        }

      
        public void GetDepartemens()
        {
            CostClient.GetAllDepartemenCompleted += new EventHandler<GetAllDepartemenCompletedEventArgs>(CostClient_GetAllDepartemenCompleted);
            CostClient.GetAllDepartemenAsync();
        }

        void CostClient_GetAllDepartemenCompleted(object sender, GetAllDepartemenCompletedEventArgs e)
        {
            CostClient.GetAllDepartemenCompleted -= new EventHandler<GetAllDepartemenCompletedEventArgs>(CostClient_GetAllDepartemenCompleted);
            Departemens = e.Result;
            foreach (var cd in CashBankIn.CashBankInDetails)
            {
                cd.Departemens = e.Result;
                if (cd.Departemen != null)
                    cd.Departemen = e.Result.FirstOrDefault(x => x.Code == cd.Departemen.Code);
            }
        }


        public void GetLastNoVoucher()
        {
            if (! string.IsNullOrEmpty(CashBankIn.CashBankAccount.KodeVoucher) )
            {
                client.GetLastNumberAsync(CashBankIn.CashBankAccount.KodeVoucher);
                client.GetLastNumberCompleted += client_GetLastNumberCompleted;

            }else
            {
                MessageBox.Show(CashBankIn.CashBankAccount.AccountName + "belum di set KodeVouchernya!");
            }
        }

        void client_GetLastNumberCompleted(object sender, GetLastNumberCompletedEventArgs e)
        {
            client.GetLastNumberCompleted -= client_GetLastNumberCompleted;
            CashBankIn.NoVoucher = e.Result;
        }
        
    }


    public class CashBankInWrapViewModel : ViewModelBase
    {
        private readonly CoaServicesClient CoaClient;
        private readonly CashBankInServicesClient client;
        private ObservableCollection<CoaDTO> _Coas;
        private CashBankInDetailDTO _CashBankInDetail;


        public CashBankInWrapViewModel()
        {
            if (!DesignerProperties.IsInDesignTool)
            {
                EditCommand = new DelegateCommand(Edit, CanEditCommand);
                DeleteCommand = new DelegateCommand(Delete, CanDeleteCommand);
                client = new CashBankInServicesClient();
                CoaClient = new CoaServicesClient();


                AddDetailCommand = new DelegateCommand(AddCashBankInDetail, CanAddDetailCommand);
                DeleteDetailCommand = new DelegateCommand(DeleteCashBankInDetail, CanDeleteDetailCommand);
                ShowAccountCommand = new DelegateCommand(ShowAccount,CanShowAccount);
                GetTotalCommand = new DelegateCommand(GetTotal, CanTotal);

                if (CashBankInViewModel.mode == Mode.Add ||
                    CashBankInViewModel.mode == Mode.Edit)
                {
                    GetCoaList();
                }
            }
        }

        public CashBankInViewModel CashBankInViewModel { get; set; }


        public ICommand EditCommand { get; set; }
        public ICommand DeleteCommand { get; set; }
        public ICommand AddDetailCommand { get; set; }
        public ICommand DeleteDetailCommand { get; set; }
        public ICommand ShowAccountCommand { get; set; }
        public ICommand GetTotalCommand { get; set; }


        public ObservableCollection<CoaDTO> Coas
        {
            get { return _Coas; }
            private set
            {
                if (Coas == value) return;
                _Coas = value;
                FirePropertyChanged("Coas");
            }
        }


        public CashBankInDetailDTO CashBankInDetail
        {
            get { return _CashBankInDetail; }
            private set
            {
                if (CashBankInDetail == value) return;
                _CashBankInDetail = value;
                FirePropertyChanged("CashBankInDetail");
            }
        }

        public bool CanEditCommand(Object param)
        {
            return true;
        }

        public bool CanDeleteCommand(Object param)
        {
            return true;
        }

        public bool CanAddDetailCommand(Object param)
        {
            return true;
        }

        public bool CanDeleteDetailCommand(Object param)
        {
            return true;
        }

        public bool CanShowAccount(Object param)
        {
            return true;
        }

        public bool CanTotal(Object param)
        {
            return true;
        }


        public void Edit(Object param)
        {
            CashBankInViewModel.mode = Mode.Edit;
            Navigation.Args = param;
            Navigation.MyNavigation.Navigate(new Uri("/EXT:CashBankIn.dll/frmAdd", UriKind.Relative));
        }

        public void Delete(Object param)
        {
            client.DeleteCompleted += client_DeleteCompleted;
            client.DeleteAsync((CashBankInDTO) param);
        }

        private void client_DeleteCompleted(object sender, AsyncCompletedEventArgs e)
        {
            client.DeleteCompleted -= client_DeleteCompleted;
            MessageBox.Show("Delete Success!");
            CashBankInViewModel.mode = Mode.Idle;
            var VM = new CashBankInViewModel();
        }

        public void ShowAccount(Object param)
        {
            CashBankInDetail = (CashBankInDetailDTO) param;
            if (CashBankInDetail.Customer != null)
            {
                CashBankInDetail.FromAccount = CashBankInDetail.Customer.Coa;
                CashBankInViewModel.GetSalesInvoiceByCustomer(CashBankInDetail.Customer);
            }
        }


        public void GetCoaList()
        {
            CoaClient.GetAllCoaCompleted += CoaClient_GetAllCoaCompleted;
            CoaClient.GetAllCoaAsync();
        }

        void CoaClient_GetAllCoaCompleted(object sender, GetAllCoaCompletedEventArgs e)
        {
            CoaClient.GetAllCoaCompleted -= CoaClient_GetAllCoaCompleted;
            Coas = e.Result;
            if (CashBankInViewModel.CashBankIn != null)
            {
                foreach (CashBankInDetailDTO CashBankInDetail in CashBankInViewModel.CashBankIn.CashBankInDetails)
                {
                    CashBankInDetail.Coas = e.Result;
                    if (CashBankInDetail.FromAccount == null) continue;
                    CashBankInDetail.FromAccount =
                        CashBankInDetail.Coas.FirstOrDefault(s => s.AccountNumber == CashBankInDetail.FromAccount.AccountNumber);
                }
            }
        }

       

        public void AddCashBankInDetail(Object param)
        {
            CashBankInDetail = new CashBankInDetailDTO();
            CashBankInDetail.Coas = Coas;
            CashBankInDetail.Departemens = CashBankInViewModel.Departemens;
            CashBankInDetail.Customers = CashBankInViewModel.Customers;

            if (CashBankInViewModel.CashBankIn.CashBankInDetails.Count > 1)
            {
                CashBankInDetail.Departemen =
                    CashBankInViewModel.CashBankIn.CashBankInDetails.FirstOrDefault().Departemen;
            }
           
            CashBankInViewModel.CashBankIn.CashBankInDetails.Add(CashBankInDetail);

            //Jika CashBank accountnya sudah dipilih maka create Debit
            if (param != null)
                if (param.GetType() == typeof(CoaDTO))
                {
                    var coaKasBank = param as CoaDTO;
                    CashBankInDetail.FromAccount =
                        CashBankInDetail.Coas.FirstOrDefault(x => x.AccountNumber == coaKasBank.AccountNumber);

                    CashBankInDetail.IsEnableKredit = false;
                }

            
        }

        public void DeleteCashBankInDetail(Object param)
        {
            CashBankInDetail = (CashBankInDetailDTO) param;
            if (CashBankInViewModel.CashBankIn.CashBankInDetails.Count > 0)
                CashBankInViewModel.CashBankIn.CashBankInDetails.Remove(CashBankInDetail);
        }

        public void GetTotal(Object param)
        {
            CashBankInViewModel.CashBankIn.TotalDebit =
                CashBankInViewModel.CashBankIn.CashBankInDetails.Sum(x => x.Debit);
            CashBankInViewModel.CashBankIn.TotalKredit = 
                CashBankInViewModel.CashBankIn.CashBankInDetails.Sum(x => x.Kredit);
            CashBankInViewModel.CashBankIn.Balance = CashBankInViewModel.CashBankIn.TotalDebit -
                                                     CashBankInViewModel.CashBankIn.TotalKredit;

        }
        
     
    }
}